package com.example.project.framework;

import com.example.project.action.ActionUtil;
import com.example.project.base.BaseApi;
import com.example.project.base.ResultBean;
import com.example.project.exception.BusinessException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用来统一封装异常信息，可以在产生异常的时候同时将错误信息进行封装成需要的格式：比如JSON、XML等
 *
 * @author Chenth
 */
public class BaseController extends BaseApi {
    /**
     * 异常控制，这便是异常细节可控，将来可用于支持国际化（异常信息国际化）
     **/
    @ExceptionHandler(Exception.class)
    @ResponseStatus(value = HttpStatus.OK)
    public @ResponseBody ResultBean handleException(Exception ex, HttpServletRequest request, HttpServletResponse response) {
        //写入错误日志
        String requestUrl = request.getRequestURI().replaceFirst(request.getContextPath(), "");
        String ipAddress = request.getHeader("X-Real-IP") == null ? request.getRemoteAddr() : request.getHeader("X-Real-IP");
        logger.error("**********************REQUEST-URL:{}***********************",requestUrl);
        logger.error("**********************IP-ADRESS:{},SessionID:{}",ipAddress,request.getSession().getId());
        logger.error("**********************ERROR HAPPEND PARAM:{}",ActionUtil.getActionParam());
        logger.error(ex.getMessage(), ex);

        if (ex instanceof BusinessException) {
            return fail(ex.getMessage());
        } else {//未知bug
            return fail("系统崩溃，请联系管理员！");
        }
    }
}
